package com.ceicei.taobaoke.api.shangpin;

import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ceicei.project.dal.dataobject.CeiceiItemDO;
import com.ceicei.project.dal.dataobject.CeiceiItemsPriceLogDO;
import com.ceicei.project.dal.dataobject.CeiceiPromotionLogDO;
import com.ceicei.taobaoke.TaobaoMain;
import com.ceicei.taobaoke.api.util.BaseTaoApiRequestTest;
import com.ceicei.util.CeiceiConstants;
import com.ceicei.util.TaobaoResultCode;
import com.taobao.api.domain.PromotionInItem;
import com.taobao.api.request.UmpPromotionGetRequest;
import com.taobao.api.response.UmpPromotionGetResponse;
import com.zhz.project.common.util.alibaba.StringUtil;

public class UmpPromotionGetTest extends BaseTaoApiRequestTest {
    private static Log logger = LogFactory.getLog(UmpPromotionGetTest.class);

    /**
     * 调用淘宝API，获取价格并保存
     *
     * @param ceiceiItemDO
     * @param single 
     */
    public TaobaoResultCode callTaobaoAPI(CeiceiItemDO ceiceiItemDO, boolean single) {
        try {
            //每个商品处理前睡眠
            waitSomeTime(500);

            //构造Request
            UmpPromotionGetRequest req = new UmpPromotionGetRequest();
            req.setItemId(ceiceiItemDO.getUrlId());
            UmpPromotionGetResponse response;

            response = client.execute(req);

            //调用成功
            if (response.isSuccess() && response.getPromotions() != null) {

                List<PromotionInItem> promotionInItemList = response.getPromotions()
                    .getPromotionInItem();

                if (promotionInItemList != null && promotionInItemList.size() > 0) {

                    PromotionInItem promotionInItem = promotionInItemList.get(0);

                    saveCeiceiPromotionLog(ceiceiItemDO, promotionInItem);
                    savePrice(ceiceiItemDO, promotionInItem, single);
                    return TaobaoResultCode.SUCCESS;
                } else {
                    //该商品没有优惠
                    //                    logger.error(" 该商品没有优惠\t" + ceiceiItemDO.getItemid());
                    TaobaoMain.nopromotionList.add(" 该商品没有优惠\t" + ceiceiItemDO.getItemid());
                    return TaobaoResultCode.NO_PROMOTION;
                }
            }
            //商品不存在
            else if (StringUtil.equals(response.getErrorCode(), CeiceiConstants.ERROR_CODE_15)) {
                //                logger.error("促销价格处理-未成功" + ceiceiItemDO.getItemid() + "\t商品不存在");
                TaobaoMain.promotionerrorList.add("促销价格处理-未成功" + ceiceiItemDO.getItemid()
                                                  + "\t商品不存在");
                return TaobaoResultCode.NOT_EXIST;
            }
            //调用次数超过规定
            else if (StringUtil.equals(response.getErrorCode(), CeiceiConstants.ERROR_CODE_7)) {
                waitSomeTime(1500);
                //                logger.error("促销价格处理-未成功" + ceiceiItemDO.getItemid() + "\t调用次数超过规定");
                //                TaobaoMain.promotionerrorList.add("促销价格处理-未成功" + ceiceiItemDO.getItemid()
                //                                                  + "\t调用次数超过规定");
                return TaobaoResultCode.ACCESS_CONTROL_LIMITED;
            } //该商品已被删除
            else if (StringUtil.equals(response.getErrorCode(), CeiceiConstants.ERROR_CODE_530)) {
                //                logger.error("促销价格处理-未成功" + ceiceiItemDO.getItemid() + "\t该商品已被删除");
                TaobaoMain.promotionerrorList.add("促销价格处理-未成功" + ceiceiItemDO.getItemid()
                                                  + "\t该商品已被删除");
                return TaobaoResultCode.DELETED;
            } else {
                //                logger.error("促销价格处理-未成功" + ceiceiItemDO.getItemid() + "\t"
                //                             + ceiceiItemDO.getUrlId() + "\t" + response.getErrorCode() + "\t"
                //                             + response.getBody());
                TaobaoMain.promotionerrorList.add("促销价格处理-未成功" + ceiceiItemDO.getItemid() + "\t"
                                                  + ceiceiItemDO.getUrlId() + "\t"
                                                  + response.getErrorCode() + "\t"
                                                  + response.getBody());
                //调用失败，睡眠1s
                waitSomeTime(1000);
            }
        } catch (Exception e) {
            logger.error("调用淘宝API时发生异常", e);
            //调用失败，睡眠1s
            waitSomeTime(1000);
        }
        return TaobaoResultCode.EXCEPTION;
    }

    /**
     * 构造CeiceiPromotionLogDO对象，并添加到数据库
     *
     * @param ceiceiItemDO
     * @param promotionInItem
     */
    private void saveCeiceiPromotionLog(CeiceiItemDO ceiceiItemDO, PromotionInItem promotionInItem) {

        if (StringUtil.isBlank(promotionInItem.getItemPromoPrice())) {
            return;
        }

        float price = Float.parseFloat(promotionInItem.getItemPromoPrice());

        //        logger.info("促销价格:" + ceiceiItemDO.getItemid() + "\t" + ceiceiItemDO.getUrlId() + "\t"
        //                    + ceiceiItemDO.getTitle() + "\t" + promotionInItem.getItemPromoPrice());
        TaobaoMain.promotionList.add("该商品有促销:" + ceiceiItemDO.getItemid() + "\t"
                                     + promotionInItem.getItemPromoPrice() + "\t"
                                     + ceiceiItemDO.getTitle());
        //保存淘宝商品促销信息
        CeiceiPromotionLogDO ceiceiPromotionLog = new CeiceiPromotionLogDO();

        ceiceiPromotionLog.setItemid(ceiceiItemDO.getItemid());
        ceiceiPromotionLog.setPromotionId(promotionInItem.getPromotionId());
        ceiceiPromotionLog.setPromotionName(promotionInItem.getName());
        ceiceiPromotionLog.setPromotionDesc(promotionInItem.getDesc());
        ceiceiPromotionLog.setPromotionPrice(price);
        ceiceiPromotionLog.setPromotionOtherNeed(promotionInItem.getOtherNeed());
        ceiceiPromotionLog.setPromotionOtherSend(promotionInItem.getOtherSend());
        ceiceiPromotionLog.setPromotionStartTime(promotionInItem.getStartTime());
        ceiceiPromotionLog.setPromotionEndTime(promotionInItem.getEndTime());
        ceiceiPromotionLog.setCreateTime(new Date());
        ceiceiPromotionLogDAO.insert(ceiceiPromotionLog);
    }

    /**
     * 
     * 保存获取的最新价格
     *
     * @param itemid
     * @param price
     * @param source
     * @return
         */
    private void savePrice(CeiceiItemDO ceiceiItemDO, PromotionInItem promotionInItem,
                           boolean single) {
        if (StringUtil.isBlank(promotionInItem.getItemPromoPrice())) {
            return;
        }
        //查看最后一次的价格
        CeiceiItemsPriceLogDO old = ceiceiItemsPriceLogDAO.getLastPriceByItemid(ceiceiItemDO
            .getItemid());

        float price = Float.parseFloat(promotionInItem.getItemPromoPrice());

        //不为空且价格没有变动，不需要处理
        if (old != null && price == old.getPrice()) {
            TaobaoMain.nopromotionpricechangeList.add("促销价格没有变化，不插入ceicei_items_price_log:"
                                                      + ceiceiItemDO.getItemid() + "\t" + price);
            //            logger.error("促销价格处理:" + ceiceiItemDO.getItemid() + "\t" + price + "\t价格没有变化，不插入该价格");
            return;
        }
        TaobaoMain.promotionpricechangeList.add("促销价格有变化-插入ceicei_items_price_log:"
                                                + ceiceiItemDO.getItemid() + "\t" + price);

        //其他情況下需要插入新的价格 
        CeiceiItemsPriceLogDO ceiceiItemsPriceLogDO = new CeiceiItemsPriceLogDO();

        ceiceiItemsPriceLogDO.setItemid(ceiceiItemDO.getItemid());
        ceiceiItemsPriceLogDO.setPrice(Float.parseFloat(promotionInItem.getItemPromoPrice()));
        ceiceiItemsPriceLogDO.setPriceType(CeiceiConstants.price_type_promotion);
        ceiceiItemsPriceLogDO.setSource(ceiceiItemDO.getSource());
        ceiceiItemsPriceLogDO.setCreatetime(new Date());
        if (single) {
            ceiceiItemsPriceLogDO.setSmsed(CeiceiConstants.SMSED_NO_NEED);
            ceiceiItemsPriceLogDO.setMailed(CeiceiConstants.MAILED_NO_NEED);
        }
        ceiceiItemsPriceLogDAO.insert(ceiceiItemsPriceLogDO);

    }
}
